/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import exceptions.GenericException;
import java.util.Iterator;
import java.util.List;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;

/**
 *
 * @author tomasz
 */
public class FirmaDAO implements Firma{
    
    private SessionFactory sessionFactory;
    private HibernateTemplate hibernateTemplate;

    public void setSessionFactory(SessionFactory  sessionFactory) {
            this.sessionFactory = sessionFactory;
            this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

    public void addFirma(model.Firma firma) {
        try{
            
            this.hibernateTemplate.saveOrUpdate(firma);
            
        }catch(DataAccessException accessException){
            
           throw new GenericException(accessException.getMessage() );
           
        }
    }

    public List allFirma() {
        
        Session session = this.sessionFactory.openSession();
        List<model.Firma> ta =  session.createQuery("from Firma").list();
        return ta;
        
    }
    
        public model.Firma findFirmaId(int id) {
          
//      model.Firma firma = (model.Firma) this.hibernateTemplate.get(model.Firma.class, id);

        Session session = this.sessionFactory.openSession();
        model.Firma firma = (model.Firma) session.createQuery("from model.Firma WHERE idFirma="+id).uniqueResult();
        
        return firma;

    }

        
    public List allFirmaInvi() {
        
        Session session = this.sessionFactory.openSession();
        
        SQLQuery  ta = session.createSQLQuery("select f.* from am.firma f left join am.Account a  on f.id_firma=a.id_firma where a.id_account is null");
        ta.addEntity(model.Firma.class);
        List fir =ta.list(); 
        
        return fir;
        
    }

    public List allFirmaInvitation() {
       Session session = this.sessionFactory.openSession();
        
        SQLQuery  ta = session.createSQLQuery("select f.*, max(a.date_send) as datesend, MAX(a.date_create_environment), MAX(a.importance_date), MAX(a.copy) from am.account a left join am.firma f on a.id_firma=f.id_firma group by f.id_firma,f.name,f.city,f.street,f.number,f.first_name,f.last_name ,f.email,f.country,f.tel,f.name,f.date_create order by datesend asc");
        ta.addEntity(model.Firma.class);
        //ta.addEntity(model.Account.class);
        List fir =ta.list(); 
        return fir;
    }
    
}
